package com.itheima.servlet;



import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@WebServlet("/respondDemo5")
public class ResponsDemo5 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        /*//1.获取文件路径（绝对路径）
        ServletContext context = getServletContext();
        //通过文件的虚拟路径， 获取文件的绝对路径

        String filename = context.getRealPath("/uploads/娜美.png");
        filename = URLEncoder.encode(filename, "utf-8");
        //2.通过文件路径构建一个字节输入流
        InputStream fis = new FileInputStream(filename);
        //3.设置响应消息头
        response.setHeader("Content-Type","application/octet-stream");
        //注意下载的时候，设置响应正文的MIME类型，用application/octet-stream
        response.setHeader("Content-Disposition","attachment;filename=娜美.png");
        //告知浏览器以下载的方式打开
        //4.使用响应对象的字节输出流输出
        ServletOutputStream outputStream = response.getOutputStream();
        int len=0;
        byte[] bytes = new byte[1024];
        while ((len=fis.read(bytes))!=-1){
          outputStream.write(bytes,0,len);
        }
        fis.close();*/
        //获取下载文件名
        String filename = request.getParameter("filename");
//       读取服务器文件获取输入流
        InputStream in = getServletContext().getResourceAsStream("/uploads/"+filename);
       //获取浏览器内核
        String agent = request.getHeader("user-agent");
        filename= DownloadDemo5.getFileName(agent,filename);
        //设置响应头通知浏览器一附件方式处理返回内容
        response.setHeader("content-Disposition","attachment;filename="+filename);
        //获取字节输出流
        ServletOutputStream out = response.getOutputStream();
        //Io流拷贝
         IOUtils.copy(in,out);

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}
